package cn.tedu.controller;

import cn.tedu.pojo.Student;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;

@RestController
@RequestMapping("stu")
@CrossOrigin//放行所有的请求,解决跨域问题
public class Stucontroller {

    @RequestMapping("add")
    public Student add(Student s) throws Exception {
        System.out.println(s);
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql:///cgb2104?characterEncoding=utf8&useSSL=false";
        Connection conn = DriverManager.getConnection(url,"root","admin123");
        String sql = "insert into student values(?,?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        //给SQL设置参数
        ps.setString(1,s.getName());
        ps.setInt(2,s.getAge());
        ps.setInt(3,s.getSex());
        ps.setInt(4,s.getEdu());
        String ho = Arrays.toString(s.getHobby());
        ps.setString(5,ho.substring(1,ho.length()-1));
        //执行sql语句
        ps.executeUpdate();
        //释放资源
        ps.close();
        conn.close();
        System.out.println("数据入库成功！");
        return s;
    }
}
